﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Drawing.Printing;
using aoprinter.Model;
using aoprinter.IO;
using aoprinter.Draw;
using aoprinter.Core;

namespace aoprinter
{
    /// <summary>
    /// an other printer's entry class
    /// </summary>
    public class AOPrinter
    {
        private PrintDocument _doc;
        private ModReport _report;
        private Drawer _drawer;
        private int _imageIndex = 0;

        public AOPrinter()
        {
            _doc = new PrintDocument();
            _doc.PrintPage += new PrintPageEventHandler(_doc_PrintPage);
        }

        public PrintDocument Document
        {
            get
            {
                return _doc;
            }
        }

        public void SetData(string xmlPath, PrinterData data = null, ModPrinterSetting setting = null)
        {
            if (_drawer == null)
            {
                _report = ReportIO.Read(xmlPath);
                ReportDataBinder.Bind(_report, data);
                setting.PageSetting.PrinterSettings.PrintFileName =
                    string.IsNullOrWhiteSpace(_report.ReportName) ? string.Empty : _report.ReportName;
                _drawer = new Drawer(_report.ReportID, setting);
                _report.Print(_drawer);
                _imageIndex = 0;
                if (setting != null)
                {
                    _doc.PrinterSettings = setting.PrinterSetting;
                    _doc.DefaultPageSettings = setting.PageSetting;
                }
            }
        }

        public int PageTotal
        {
            get
            {
                return _report.PageTotal;
            }
        }

        public void Print()
        {
            _imageIndex = 0;
            _doc.Print();
        }

        public ModReport GetReport()
        {
            return _report;
        }

        public void ClearDrawPage()
        {
            if (_drawer != null)
            {
                _drawer.ClearDrawPage();
            }
        }

        void _doc_PrintPage(object sender, PrintPageEventArgs e)
        {
            Image image = _drawer.GetImage(_imageIndex);
            e.HasMorePages = false;
            if (image != null)
            {
                Matrix matrix = new Matrix();
                matrix.Scale(_report.ScaleX, _report.ScaleY);
                e.Graphics.MultiplyTransform(matrix, MatrixOrder.Append);
                e.Graphics.PageUnit = GraphicsUnit.Pixel;
                e.Graphics.DrawImage(image, Point.Empty);
                if (++_imageIndex < _drawer.TotalNumber)
                {
                    e.HasMorePages = true;
                }
                image.Dispose();
                GC.Collect();
            }
        }
    }
}